var fs = require('fs');
var path = require('path');
var imgHandle = require('./ImageHandle');
var buildList = [];

function loadFile(origin, newFolder, imageList = []) {
    const files = fs.readdirSync(origin);
    files.forEach((item, index) => {
        var fullPath = path.join(origin, item);
        const stat = fs.statSync(fullPath);
        if (stat.isDirectory()) {
            //递归读取文件
            loadFile(path.join(origin, item), path.join(newFolder, item), imageList);
        } else {
            var extname = path.extname(fullPath);
            if (extname == '.png' || extname == '.jpg') {
                var newPath = path.join(newFolder, item);
                const _stat = fs.statSync(newPath);
                fullPath = fullPath.replace("public/", "");
                newPath = newPath.replace("public/", "");
                var image = [{
                    image: fullPath,
                    size: (stat.size / (1024 * 1024)).toFixed(2) + "mb"
                }, {
                    image: newPath,
                    size: (_stat.size / (1024 * 1024)).toFixed(2) + "mb"
                }];
                imageList.push(image);
            }
        }
    });
    return imageList;
}
Array.prototype.remove = function (val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

function loadImageList(min, max, callBack) {
    var _query = min + "_" + max;
    var _newFolder = './public/build/' + _query;
    fs.access(_newFolder, fs.constants.F_OK, (err) => {
        if (!err) {
            //存在
            var _exFilePath = path.join(_newFolder, _query + ".csv");
            console.log(_exFilePath);
            fs.access(_exFilePath, fs.constants.F_OK, (_err) => {
                console.log(`${_exFilePath} ${_err ? '不存在' : '存在'}`);
                if (_err) {
                    //构建中
                    callBack([]);
                } else {
                    // 存在直接返回
                    var imageList = [];
                    loadFile("./public/images", _newFolder, imageList);
                    callBack(imageList);
                }
            });
        } else {
            //不存在
            callBack([]);
            (async () => {
                buildList.push(_query);
                const res = await imgHandle.handleImage(min, max);
                if (res) {
                    console.log("ssssss");
                    buildList.remove(_query);
                }
            })();
        }
    });

}

module.exports = (function () {
    return {
        list: function (req, res) {
            console.log(req.header);
            res.send([]);
        },
        index: function (req, res) {
            console.log(req.query);
            res.type('html');
            var _imageList = [];
            if (req.query.hasOwnProperty('min') && req.query.hasOwnProperty('max')) {
                var min = req.query.min;
                var max = req.query.max;
                var _query = min + "_" + max;
                var csv = '';
                loadImageList(min, max, (list) => {
                    if (list.length > 0) {
                        csv = 'build/' + _query + "/" + _query + ".csv";
                    }
                    res.render('index', {
                        images: list,
                        csv: csv
                    });
                });
            } else {
                res.render('index', {
                    images: _imageList,
                    csv: ''
                });
            }

        }
    }
})();